#pragma once

#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

namespace Local_Inetaddr
{
    class Inetaddr
    {
    public:
        /**************Inetaddr******************/
        Inetaddr(struct sockaddr_in &addr)
            : _addr(addr)
        {
            char lo_buffer[64];
            inet_ntop(AF_INET, &_addr.sin_addr, lo_buffer, sizeof(_addr));
            _ip = lo_buffer;
            _port = ntohs(_addr.sin_port);
        }
        Inetaddr(const std::string &ip, uint16_t port)
            : _ip(ip),
              _port(port)
        {
            memset(&_addr, 0, sizeof(_addr));
            _addr.sin_family = AF_INET;
            inet_pton(AF_INET, _ip.c_str(), &_addr.sin_addr);
            _addr.sin_port = htons(_port);
        }
        Inetaddr(uint16_t port)
            : _ip(),
              _port(port)
        {
            memset(&_addr, 0, sizeof(_addr));
            _addr.sin_family = AF_INET;
            _addr.sin_addr.s_addr = INADDR_ANY;
            _addr.sin_port = htons(_port);
        }

        /**************Get******************/
        std::string GetIp() { return _ip; }
        uint16_t GetPort() { return _port; }
        std::string GetStrAddr() { return _ip + " : " + std::to_string(_port); }
        const struct sockaddr_in &GetAddr_in() { return _addr; }
        const struct sockaddr *GetAddrPtr() { return (const struct sockaddr *)&_addr; }
        socklen_t GetAddrSize() { return sizeof(_addr); }

        /*****************operator******************* */
        // 重载==
        bool operator==(const Inetaddr &input)
        {
            return (input._ip == _ip && input._port == _port);
        }
        // 重载！=
        bool operator!=(const Inetaddr &input)
        {
            return !this->operator==(input);
        }

    private:
        struct sockaddr_in _addr;
        std::string _ip;
        uint16_t _port;
    };
}